package com.innazis.jfrogsurvey;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.innazis.jfrogsurvey.backendmanager.ModelManager;
import com.innazis.jfrogsurvey.backendmanager.ModelManagerListener;
import com.innazis.jfrogsurvey.backendmanager.ParserUtility;
import com.innazis.jfrogsurvey.backendmanager.task.UpdateSurveysTask;
import com.innazis.jfrogsurvey.config.CommonUtilities;
import com.innazis.jfrogsurvey.config.Constants;
import com.innazis.jfrogsurvey.managers.SurveyManager;
import com.innazis.jfrogsurvey.obj.ServerResponse;
import com.innazis.jfrogsurvey.obj.SurveyObj;
import com.innazis.jfrogsurvey.utility.DialogUtil;
import com.innazis.jfrogsurvey.zxing.CaptureActivity;

public class MainActivity extends BaseActivity implements View.OnClickListener {

	protected MainActivity self;
	private Button btnUpdate;
	private Button btnScan;
	private Button btnSendNew;
    private Button btnSendAll;
    private TextView txtCounterToday;
    private TextView txtCounterWhole;
    ArrayList<SurveyObj> surveysToSend;
    SurveyManager sManager;
    Drawable d;
    private String senderID = "Unknown"; // temporary, user enters his name when installs an app, save in pref

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		self = this;
		initUI();
        initData();
        initCounter();
	}

	private void initUI() {
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnUpdate.setOnClickListener(this);
		btnScan = (Button) findViewById(R.id.btnScan);
		btnScan.setOnClickListener(this);
		btnSendNew = (Button) findViewById(R.id.btnSendNew);
        btnSendNew.setOnClickListener(this);
        btnSendAll = (Button) findViewById(R.id.btnSendAll);
        btnSendAll.setOnClickListener(this);
        txtCounterToday = (TextView)findViewById(R.id.txtToday);
        txtCounterWhole = (TextView)findViewById(R.id.txtWholePeriod);
        d = btnSendNew.getBackground();
	}

    private void initData() {
        if (sManager == null) {
            sManager = new SurveyManager(self);
        }
        ArrayList<SurveyObj> lstSurveys = new ArrayList<SurveyObj>();
        lstSurveys = sManager.getAllSurveys();

        if(lstSurveys.size()==0)
            updateSurveyWithVolley();
    }

    private void initCounter() {
        if (sManager == null) {
            sManager = new SurveyManager(self);
        }
        String whole = String.valueOf(sManager.getWholePeriodCounter());
        txtCounterWhole.setText(whole);
        String today = String.valueOf(sManager.getTodaysCounter());
        txtCounterToday.setText(today);
        if (sManager.notSentSurveys() > 0){
            btnSendNew.setBackgroundColor(getResources().getColor(R.color._alert));
        }
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnScan:
            startActivity(new Intent(MainActivity.this, CaptureActivity.class));
			break;
		case R.id.btnUpdate:
			updateSurveyWithVolley();
            initCounter();
			break;
        case R.id.btnSendNew:
            sendSurveysToServer(true);
            break;
		case R.id.btnSendAll:
            sendSurveysToServer(false);
			break;
		default:
			break;
		}
	}

	private void updateSurveyWithVolley(){
	showLoading();
	ModelManager.getInstance(self).updateSurvey(self, new ModelManagerListener() {
		@Override
		public void onSuccess(Object object) {
			Log.d("ModelManager","Response : "+object.toString());
			JSONObject obj=(JSONObject)object;
			JSONArray arrJsonSurvey;
			ArrayList<SurveyObj> arrSurvey = null;
			try {
				arrJsonSurvey = obj.getJSONArray("data");
				if(arrJsonSurvey!=null&&arrJsonSurvey.length()>0)
				{
					arrSurvey=ParserUtility.parserListCategory(arrJsonSurvey);
				}
				//Store question to local database
				 if (arrSurvey.size()> 0) {
                    if (sManager == null) {
                        sManager = new SurveyManager(self);
                    }
			            sManager.deleteAllSurveys();
			            for (SurveyObj item : arrSurvey){
			                sManager.addSurvey(item);
			            }
                     initCounter();
                     showToast("The survey " + arrSurvey.get(0).get_survey_name() + " updated, the old stuff removed.");
				 }
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			hideLoading();
		}
		public void onError(String message) {
        // TODO Auto-generated method stub
        hideLoading();
        DialogUtil.alert(self,message);
    }
});
}

    private void sendSurveysToServer (boolean is_new) {
        surveysToSend = null;
        senderID = CommonUtilities.getInstance(self).pullPreferences(self,
                Constants.USER);
        try {
            if (sManager == null) {
                sManager = new SurveyManager(self);
            }
        surveysToSend = (is_new) ? sManager.getNotSentSurveys() : sManager.getAllSurveys();
        if (surveysToSend.size() < 1) {
            DialogUtil.alert(self, R.string.no_survey_to_send);
            return;
        }
        ModelManager.getInstance(self).sendData(self, surveysToSend, senderID, new ModelManagerListener() {
            @Override
            public void onSuccess(Object object) {
                JSONObject obj=(JSONObject)object;
                ServerResponse response = new ServerResponse();
                if (object != null && ((JSONObject) object).length()>0) {
                    response.set_return_code(ParserUtility.getIntValue(obj,Constants.return_code_p));
                    response.set_message(ParserUtility.getStringValue(obj, Constants.message_p));
                }
                if (response.get_return_code() >= 0){
                    if (sManager == null) {
                        sManager = new SurveyManager(self);
                    }
                    for (SurveyObj item : surveysToSend){
                        item.set_is_sent(true);
                        sManager.updateSentStatus(item);
                    }
                    if (sManager.notSentSurveys() == 0){
                        btnSendNew.setBackgroundDrawable(d);
                    }
                    //DialogUtil.alertThanks(self, R.string.success_sending);
                    showToast(R.string.success_sending);
                }
            }
            public void onError(String message) {
                // TODO Auto-generated method stub
                DialogUtil.alert(self, R.string.error_sending);
            }
        });
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

}
